<template>
  <view class="min-h-100vh bg-[#f7f8fa] pb-[40rpx]">
    <wd-navbar 
      title="错题复习" 
      custom-class="navbar-custom" 
      :bordered="false" 
      fixed 
      placeholder 
      safeAreaInsetTop
      left-arrow
      @click-left="goBack"
    ></wd-navbar>
    <!-- 题目列表 -->
    <scroll-view class="p-[30rpx_30rpx_20rpx] box-border" scroll-y>
      <!-- 空状态 -->
      <view v-if="questionList.length === 0" class="empty-state">
        <text class="text-[35rpx] color-[#969799]">暂无错题</text>
      </view>

      <!-- 题目列表 -->
      <view
        v-for="(question, index) in questionList"
        :key="question.id"
        class="bg-white rounded-[12rpx] p-[30rpx] mb-[20rpx]"
      >
        <!-- 题目标题 -->
        <view class="text-[30rpx] color-[#323233] leading-[1.6] mb-[20rpx] font-500">
          {{ index + 1 }}. {{ question.title }}
        </view>

        <!-- 选择题和判断题的选项展示 -->
        <view class="mb-[16rpx]">
          <view
            v-for="option in question.options"
            :key="option.key"
            class="flex items-center py-[20rpx]"
          >
            <!-- 判断用户是否选择了该选项以及是否答对 -->
            <view 
              :class="getOptionIconClass(question, option)"
            ></view>
            <text 
              class="text-[28rpx] leading-[1.5]"
              :style="{color: getOptionTextColor(question, option)}"
            >
              {{ option.key }}. {{ option.value }}
            </text>
          </view>
        </view>

        <!-- 正确答案提示 -->
        <view class="text-[26rpx] color-[#07c160]">
          正确答案：{{ question.correctAnswerKeys.join('、') }}
        </view>
      </view>
    </scroll-view>

    <!-- 提交按钮 -->
    <view class="exam-footer" v-if="questionList.length > 0">
      <wd-button custom-class="submit-btn" size="large" block @click="handleToExercise">
        <text class="text-[40rpx] line-height-[56rpx] color-[#C00C0C] text-shadow-[2rpx_0rpx_2rpx_rgba(0,0,0,0.1)]">
          刷错题，提高正确率!
        </text>
      </wd-button>
    </view>

  </view>
</template>

<script setup>
import { ref } from 'vue'
import { wrongReview } from '@/api/exam.js'

const title = ref('') // 标题
const questionList = ref([]) // 题目列表

// 字母表，用于生成选项 key
const OPTION_KEYS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']

onLoad((options) => {
  // 获取错题数据
  loadWrongQuestions()
})

definePage({
  style: {
    navigationStyle: 'custom',
  },
})

// 加载错题数据
const loadWrongQuestions = () => {
  wrongReview({}).then(res => {
    console.log('错题数据：', res)
    // 处理空数据情况
    if (res.length === 0) {
      questionList.value = []
      return
    }
    
    // 转换数据格式
    questionList.value = res.map(item => {
      const question = {
        id: item.id,
        cate: item.cate, // 1=判断, 2=单选, 4=多选
        title: item.text,
        image: item.image,
        options: [],
        correctAnswerIds: item.answer || [], // 正确答案的 option id 数组
        correctAnswerKeys: [], // 正确答案的字母表示
        userAnswerIds: item.user_answer || [], // 用户回答的 option id 数组
      }
      
      // 处理选项
      if (item.cate === 1) {
        // 判断题：answer: [0]=错误, [1]=正确
        question.options = [
          { id: 1, key: 'A', value: '正确', isCorrect: item.answer[0] === 1 },
          { id: 0, key: 'B', value: '错误', isCorrect: item.answer[0] === 0 },
        ]
        // 设置正确答案的 key
        question.correctAnswerKeys = item.answer[0] === 1 ? ['A'] : ['B']
      } else {
        // 单选题/多选题：为每个选项添加 key (A, B, C, D...)
        question.options = (item.options || []).map((opt, index) => {
          const isCorrect = item.answer.includes(opt.id)
          return {
            id: opt.id,
            key: OPTION_KEYS[index],
            value: opt.text,
            image: opt.image,
            isCorrect: isCorrect
          }
        })
        // 找出正确答案的 key
        question.correctAnswerKeys = question.options
          .filter(opt => opt.isCorrect)
          .map(opt => opt.key)
      }
      
      return question
    })
    
    console.log('转换后的错题列表：', questionList.value)
  }).catch(err => {
    uni.hideLoading()
    console.error('获取错题失败：', err)
    uni.showToast({
      title: '获取错题失败',
      icon: 'none'
    })
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 进入错题练习
const handleToExercise = () => {
  uni.navigateTo({
    url: `/pages-children/examQuestion/index?type=wrongExercise`,
  })
}

// 获取选项图标样式
const getOptionIconClass = (question, option) => {
  const isUserAnswered = question.userAnswerIds?.includes(option.id) // 用户是否选择了这个选项
  const isCorrect = question.correctAnswerIds?.includes(option.id) // 这个选项是否是正确答案
  
  if (!isUserAnswered) {
    // 用户没选这个选项
    return 'normalIcon'
  }
  
  // 用户选择了这个选项
  if (isCorrect) {
    // 答对了
    return 'rightIcon'
  } else {
    // 答错了
    return 'errIcon'
  }
}

// 获取选项文字颜色
const getOptionTextColor = (question, option) => {
  const isUserAnswered = question.userAnswerIds?.includes(option.id) // 用户是否选择了这个选项
  const isCorrect = question.correctAnswerIds?.includes(option.id) // 这个选项是否是正确答案
  
  if (!isUserAnswered) {
    // 用户没选这个选项，使用默认颜色
    return '#323233'
  }
  
  // 用户选择了这个选项
  if (isCorrect) {
    // 答对了，绿色
    return '#07c160'
  } else {
    // 答错了，红色
    return '#d91515'
  }
}

</script>

<style lang="scss" scoped>
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 200rpx 0;
}

.normalIcon {
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid #dcdee0;
  border-radius: 50%;
  margin-right: 16rpx;
  flex-shrink: 0;
}


.exam-footer {
  padding: 60rpx 0 80rpx 0;
  display: flex;
  justify-content: center;
  
  :deep(.submit-btn) {
    width: 564rpx !important;
    height: 100rpx !important;
    background-image: url('/static/images/bg11.png') !important;
    background-size: 100% 100% !important;
    background-repeat: no-repeat !important;
    background-position: center !important;
    background-color: transparent !important;
    border: none !important;
  }
}
</style>
